<?php
/* ************************************************** *\
 * @company		: NovaITech							  *	
 * @author		: van.vo@novaitech.com				  * 
 * @copyright	: 2012								  * 
 * ================================================== *
 * @date		: {creation_date}
 * @project		: 
 * @description	: {description}
 *		- 
 *
\* ************************************************** */
class Statistics extends MY_Controller {
    
    function __construct( ) {
        parent::__construct( );
		$this->load->library( array( 'form_validation', 'table' ) );		
		$this->load->helper( array( 'form', 'url' ) );
		$this->load->model( 'CodeGenerator_model', '', TRUE );
		$this->load_template();
	}	
	
	function index( ){
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'transaction_add' ];
        $rules                  =         array(
		array('field_id' => 'khachhang','label' => 'Khách hàng','control' => 'Array','width' => '10%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
		array('field_id' => 'Serv_FullName','label' => 'Dịch vụ','control' => 'Array','width' => '20%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
		array('field_id' => 'EE_Name','label' => 'Người típ','control' => 'Array','width' => '10%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
		array('field_id' => 'Create_Dt','label' => 'Ngày tạo','control' => 'time','width' => '10%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
		array('field_id' => 'Price','label' => 'Giá','control' => 'vnd','width' => '10%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
		array('field_id' => 'Price_Serv','label' => 'Tien DV','control' => 'vnd','width' => '10%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
		array('field_id' => 'Discount_Percent','label' => 'Giảm %','control' => 'Array','width' => '10%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
		array('field_id' => 'Money','label' => 'Thành tiền','control' => 'vnd','width' => '10%', 'class' => 'last', 'style' => ''));
        $this->data[ 'rules' ]  =   $rules;
       
		$selected_cat=$this->input->post('theo');
		$time=$this->input->post('statistics_dt');
		$time_from=$this->input->post('statistics_dt_from');
		$time_to=$this->input->post('statistics_dt_to');
		if(empty($time))
			$time = date("d/m/Y",time());
		if(empty($time_from))
			$time_from = date("d/m/Y",time());
		if(empty($time_to))
			$time_to = date("d/m/Y",time());
		$this->data['time'] = $time;
		$this->data['time_from'] = $time_from;
		$this->data['time_to'] = $time_to;
		if(empty($selected_cat)) $selected_cat = 'D';
		$combobox_cats['D']="Thống kê theo ngày";
		$combobox_cats['W']="Thống kê theo tuần";
		$combobox_cats['M']="Thống kê theo tháng";
		$combobox_cats['Y']="Thống kê theo năm";
		$combobox_cats['CM']="Thống kê theo mốc";
		$this->data['combobox_cats']=form_dropdown('theo', $combobox_cats,$selected_cat);
		if($selected_cat == "CM"){
			$limit['datemin']= $this->convertDatetoTimeStamp($time_from,1);
			$limit['datemax']= $this->convertDatetoTimeStamp($time_to,0);
		}else
			$limit = $this->getLimit($selected_cat,$time);
		// print_r($limit);
		// die;
        // Make header
        // --------------------------------------------------
        $header = array( );
        foreach( $rules as $item ){
            $header[ ] = $item[ 'label' ];
        }
       
        $this->data[ 'header' ] =   $header;
		$sql = "select t.*, CONCAT(c.F_Name, ' ' , c.L_Name) as khachhang, p.SoSuat, p.Conlai,p.Tang from customer as c, transaction as t left join phieukh as p on t.Phieu_ID=p.ID where c.Cust_ID = t.Cust_ID AND t.Create_Dt >= ".$limit['datemin']." AND t.Create_Dt <= ".$limit['datemax']." and t.Completed = 2 order by t.Create_Dt";
		//$sql = "select t.Tran_ID, CONCAT(c.F_Name, ' ' , c.L_Name) as khachhang, t.* from transaction as t, customer as c where c.Cust_ID = t.Cust_ID AND t.Create_Dt > ".$limit['datemin']." AND t.Create_Dt <".$limit['datemax'];
        // $results                =   $this->CodeGenerator_model->get( 'transaction', 'Tran_ID,Cust_ID,Serv_ID,Discount_Percent,Promo_ID,Create_Dt,Money,Completed' );
        $results=$this->CodeGenerator_model->custom_query($sql,"array");
        // Make action Edit/Delete
        // --------------------------------------------------
		$sql = "select sum(Price) as gia, sum(Discount_Percent) as giam, sum(Money) as thanhtien, sum(Bonus) as bonus from transaction where Completed=2 and Create_Dt >= ".$limit['datemin']." AND Create_Dt <= ".$limit['datemax'];
		$total = $this->CodeGenerator_model->custom_query($sql,"array");
		$gia = 0; $giam=0; $thanhtien = 0; $bonus = 0;
		
		if(!empty($total)){
			$gia = $total[0]['gia'];
			$giam = $total[0]['giam'];
			$thanhtien = $total[0]['thanhtien'];
			$bonus = $total[0]['bonus'];
		}
		//lấy tiền típ
		$this->data['tientip']= $this->getTientip($limit['datemin'],$limit['datemax']);
		//end
		
		$this->data['gia'] = $gia;
		$this->data['giam'] = $giam;
		$this->data['thanhtien'] = $thanhtien;
		$this->data['bonus'] = $bonus;
		$sum_tiendv = 0;
        for( $i = 0; $i < count( $results ); $i++ ){
	       $id = array_values( $results[ $i ]);
		   $Tran_ID = $results[$i]['Tran_ID'];
		   //duyet service va nguoi duoc tip
		   $str_dv = "";
			$str_nguoitip = "";
			$tiendv = 0;
			//table tientip
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID,tt.Price,tt.Price_Serv  from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and e.EE_ID = tt.EE_ID and tt.Serv_ID = s.Serv_ID";
		   // echo $sql;die;
		   $services = $this->CodeGenerator_model->custom_query($sql,"array");
			
		   foreach($services as $t){
				$str_dv .=$t['Serv_Name']."(".$t['Name'].")"." + ";
				$str_nguoitip .= $t['Personal_ID']."(".$t['Price']."k), ";
				$tiendv +=$t['Price_Serv'];
		   }  
		   //phieu 
		   $sql = "select s.Serv_Name, ca.Name, e.Personal_ID, p.TienTip,p.SoSuat, p.Conlai,p.Price_Serv from services as s, categories as ca, employee as e, phieukh as p where p.Tran_ID='$Tran_ID' and p.EE_ID = e.EE_ID and s.Cat_ID = ca.Ca_ID and p.Serv_ID = s.Serv_ID and p.Active=1";
		   $phieus = $this->CodeGenerator_model->custom_query($sql,"array");
		   foreach($phieus as $t){
				$str_dv .="Phieu ".$t['SoSuat']." suat - con lai ".$t['Conlai']." suat - ".$t['Serv_Name']."(".$t['Name'].")"." + ";
				$str_nguoitip .= $t['Personal_ID']."(".$t['TienTip']."k), ";
				$tiendv +=$t['Price_Serv'];
		   }
		   
		   //vip
			$sql = "select s.Serv_Name, ca.Name,tt.Price,tt.Price_Serv,tt.ID from services as s, categories as ca, employee as e, tientip as tt where tt.Tran_ID='$Tran_ID' AND s.Cat_ID = ca.Ca_ID and tt.Serv_ID = s.Serv_ID and tt.Vip=1 Group by tt.ID";
		   $services = $this->CodeGenerator_model->custom_query($sql,"array");
		   foreach($services as $t){
				$str_dv .=$t['Serv_Name']."(".$t['Name'].")"."<br/><center>------</center>";
				$sql = "select e.Personal_ID, e.Name as e_Name,tv.Price,tv.Price_Serv from transaction_vip as tv, employee as e where e.EE_ID=tv.EE_ID and tv.TienTip_ID='".$t['ID']."'";
				$child=$this->CodeGenerator_model->custom_query($sql,"array");
				foreach($child as $k){
					$str_nguoitip .= $k['e_Name']."(".$k['Price']."k), ";
					// $str_dv .=$k['e_Name']."(".$k['Price_Serv']."k)";
				}
				$tiendv +=$t['Price_Serv'];
		   }
		   $sum_tiendv += $tiendv;
		   $results[$i]['Serv_FullName'] = substr($str_dv, 0, -3);
		   $results[$i]['EE_Name'] = substr($str_nguoitip,0,-2);
		   $results[$i]['Price_Serv'] = $tiendv;
        }
        
        $this->data[ 'results'        ]     =   $results;
        $this->data[ 'master_limited' ]     =   explode(',', 'Tran_ID,Cust_ID,SoSuat,Conlai,Serv_FullName,EE_Name,Bonus,khachhang,Serv_ID,Promo_ID,Price,Discount_Percent,Create_Dt,Money,Completed,Price_Serv'); 
		//lay tien dich vu cho moi nhan vien
		$results = $this->getResultsDichVu($limit['datemin'],$limit['datemax']);
		$this->data['tiendv'] = $results['rows'];
		$this->data['sum_dv'] = $sum_tiendv;
		$this->data['selected'] = $selected_cat;
		
       // $this->data[ 'action'         ]     =   array(array('id' => 'new','label' => 'New','url' => 'index.php/transaction/add/',),array('id' => 'delete','label' => 'Delete','url' => '',),);
        // $this->load->view( 'transaction_list', $this->data ); 
		$this->template->write( 'title', 'Spa - Thống kê' );
        $this->template->write_view( 'content', 'statisticst.php',$this->data );
        $this->template->render();
	}

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: View list
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function view( ){
        // Get rules from config file
        // --------------------------------------------------
	    //$rules                  =   $this->form_validation->_config_rules[ 'services_add' ];
        $rules                  =   array(array('field_id' => 'Serv_ID','label' => 'Serv_ID','control' => 'Array',),array('field_id' => 'Serv_Name','label' => 'Serv_Name','control' => 'Array',),array('field_id' => 'Serv_Name_EN','label' => 'Serv_Name_EN','control' => 'Array',),array('field_id' => 'Price','label' => 'Price','control' => 'Array',),array('field_id' => 'Create_Dt','label' => 'Create_Dt','control' => 'Array',),);
	    $this->data[ 'rules' ]  =   $rules;
       
        // Make header
        // --------------------------------------------------
	    $header = array( );
	    foreach( $rules as $item ){
	        $header[ ] = $item[ 'label' ];
	    }
       
	    $this->data[ 'header' ] =   $header;
	    $results                =   $this->CodeGenerator_model->get( 'services', 'Serv_ID,Serv_Name,Serv_Name_EN,Price,Create_Dt' );
	
        $actions  = array();
            
        
        
        // Make action Rent/Contact/Review
        // --------------------------------------------------
        for( $i = 0; $i < count( $results ); $i++ ){
            $id = array_values( $results[ $i ] );
            
            if(!empty($actions)){
                foreach ($actions as $item) {
                    $results[ $i ][ $item['action_name'] ]   = anchor( base_url( ) . 
                    'index.php/services/'. $item['action_func'] . "/" . $id[ 0 ], $item['action_name']);
                }
            }
            
        }
        
        $this->data[ 'results'        ]   =   $results;
        $this->data[ 'master_limited' ]   =   explode(',', 'Serv_ID,Serv_Name,Serv_Name_EN,Price,Create_Dt');
        $this->data[ 'custom_action'  ]   =   $actions;
 
        $this->load->view( 'services_list', $this->data ); 
    }
    
    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Manage list
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function manage( ){
        
    }
	

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Load form add new record
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function add( ){            
		$this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;
        $Serv_ID = set_value('Serv_ID');
		if(!$Serv_ID)
			$Serv_ID="SV_".uniqid();
		$this->data['temp_id'] = $Serv_ID;
		$selected_cat=$this->input->post('Cat_ID');
		$categories=$this->CodeGenerator_model->get('categories','*');
		$combobox_cats=array();
		foreach($categories as $cat){
			$combobox_cats[$cat['Ca_ID']]=$cat['Name'];
		}
		$this->data['combobox_cats']=form_dropdown('Cat_ID', $combobox_cats,$selected_cat);
        if( $this->form_validation->run( 'services_add' ) == false ){
             $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );
        }else{                            
            $data = array(
					'Serv_ID' => $Serv_ID,
                    'Serv_Name' => set_value('Serv_Name'),
					'Serv_Name_EN' => set_value('Serv_Name_EN'),
					'Time' => set_value('Time'),
					'Cat_ID' => $selected_cat,
					'Price' => set_value('Price'),
					'Create_Dt' => time()
            );
            $result = $this->CodeGenerator_model->add( 'services', $data, 'Serv_ID' );
			if( $result == ADD_SUCCESSFULLY ){
				redirect( base_url() . 'index.php/services/manage/' );
			}else if( $result == RECORD_EXISTED ){
				$this->data[ 'custom_error' ] = '<div class="form_error"><p>A record existed.</p></div>';
			}else{
				$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured.</p></div>';
			}
		}		   
		// $this->load->view( 'services_add', $this->data );   
		$this->template->write( 'title', 'Spa - Thêm dịch vụ' );
        $this->template->write_view( 'content', 'services_add.php',$this->data );
        $this->template->render();
    }	

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Load edit form.
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function edit( ){
        $this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;
        $selected_cat=$this->input->post('Cat_ID');
        if( $this->form_validation->run( 'services_edit' ) == false ){
            $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );

        }else{                            
            $data = array(
                'Serv_Name' => $this->input->post('Serv_Name'),
					'Serv_Name_EN' => $this->input->post('Serv_Name_EN'),
					'Price' => $this->input->post('Price'),
					'Cat_ID' => $selected_cat,
					'Time' => $this->input->post('Time'),
					'Create_Dt' => time()
            );
			if( $this->CodeGenerator_model->edit( 'services', $data, 'Serv_ID', $this->input->post( 'Serv_ID' ) ) == TRUE ){
				redirect( base_url( ) . 'index.php/services/manage/' );
			}else{
				$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured</p></div>';
			}
		}
		$result   =   $this->CodeGenerator_model->get( 'services', 'Serv_ID,Cat_ID,Serv_Name,Serv_Name_EN,Price,Time,Create_Dt', 'Serv_ID = "' . $this->uri->segment( 3 ) . '"', NULL, NULL, true );  
		// $this->load->view( 'services_edit', $this->data );
		if(!$selected_cat)
			$selected_cat = $result->Cat_ID;
		$categories=$this->CodeGenerator_model->get('categories','*');
		$combobox_cats=array();
		foreach($categories as $cat){
			$combobox_cats[$cat['Ca_ID']]=$cat['Name'];
		}
		$this->data[ 'result' ]  = $result;
		$this->data['combobox_cats']=form_dropdown('Cat_ID', $combobox_cats,$selected_cat);
		$this->template->write( 'title', 'Spa - Sửa dịch vụ' );
        $this->template->write_view( 'content', 'services_edit.php',$this->data );
        $this->template->render();
    }

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Delete record
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function delete( ){
        $ID =  $this->uri->segment( 3 );
        $this->CodeGenerator_model->delete(  'services', 'Serv_ID', $ID );             
        redirect( base_url( ) . 'index.php/services/manage/' );
    }       
}